import CircleState from "@/components/CircleState"
import { history, useIntl, useModel } from "@umijs/max"
import { App, Button, Card, Col, Image, Row, Select } from "antd"
import React, { useState } from "react"
import AlarmRecordsForm from "./AlarmRecordsForm"
import BoardSizeCheckModal from "./BoardSizeCheckModal"
import BoardSizeHandLabelModal from "./BoardSizeHandLabelModal"
import CutLineCheckModal from "./CutLineCheckModal"
import DeviceLockModal from "./DeviceLockModal"
import HandInnerBoard1pinModal from "./HandInnerBoard1pinModal"
import TotalboardErrorModal from "./TotalboardErrorModal"

const ProducePage: React.FC = () => {
  const { callPy } = useModel("websocketModel")
  const { message } = App.useApp()
  const {
    workingOrder,
    totalOrders,
    updateProduceData,
    firstCalError,
    firstCutLineRes,
    firstCutLineSize,
    cutBoardSizeFirst,
    catchCenter01FirstCut,
    catchCenter02FirstCut,
    notFirstCutLineRes,
    notFirstCutLineSize,
    notFirstImageSize,
    notFirstCalError,
    calcSize,
    catchCenter01,
    catchCenter02
  } = useModel("produceModel")

  const { cutPlcState, cameraGroupState, workStopState, updateWorkStopState } =
    useModel("deviceModel")
  const [searchId, setSearchId] = useState<string>("")

  const intl = useIntl()

  const onOrderSelectChange = (value: string) => {
    setSearchId(value)
  }

  const clickSearch = async () => {
    const response = await callPy("db", "search_order_from_web", [searchId])
    if (response.state) {
      message.success("搜索成功")
      updateProduceData({
        searchOrders: response.data,
        showTotalOrders: false,
        orderChoosed: response.data[0]
      })
      history.push("/order_manager")
    } else {
      message.error("搜索失败" + response.info, 5)
    }
  }

  const HandleStopProduce = async () => {
    const response = await callPy("produce", "stop_produce_from_web", [])
    if (response.state) {
      message.info("自动作业停止成功")
      updateWorkStopState(true)
    } else {
      message.error("自动作业停止失败" + response.info, 5)
    }
  }

  const reDoFirstBoard = async () => {
    const response = await callPy("produce", "re_do_first_board_from_web", [])
    if (response.state) {
      message.info("重新做首板下发成功")
    } else {
      message.error("重新做首板下发失败" + response.info, 5)
    }
  }

  const HandleStartProduce = async () => {
    const response = await callPy("produce", "start_produce_from_web", [])
    if (response.state) {
      message.success("自动作业启动成功")
      updateWorkStopState(false)
    } else {
      message.error("自动作业启动失败" + response.info, 5)
    }
  }

  const scanOrderCode = () => {
    history.push("/order_manager")
  }

  const clickOpenCutlineDir = async () => {
    const response = await callPy("produce", "open_cutline_dir_from_web", [])
    if (response.state) {
      message.success("打开切线图目录成功")
    } else {
      message.error("打开切线图目录失败" + response.info, 5)
    }
  }

  const clickOpenLogDir = async () => {
    const response = await callPy("produce", "open_log_dir_from_web", [])
    if (response.state) {
      message.success("打开日志文件目录成功")
    } else {
      message.error("打开日志文件目录失败" + response.info, 5)
    }
  }

  const clickOpenFirstBoardCutlineDir = async () => {
    const response = await callPy("produce", "open_first_board_cutline_dir_from_web", [])
    if (response.state) {
      message.success("打开首件切线目录成功")
    } else {
      message.error("打开首件切线目录失败" + response.info, 5)
    }
  }
  return (
    <div>
      <Row style={{ display: "flex", alignItems: "stretch" }}>
        <Col span={8}>
          <Card
            style={{ height: "100%" }}
            bodyStyle={{ padding: "12px" }}
            extra={
              <div style={{ display: "flex", alignItems: "center" }}>
                <Button
                  type="primary"
                  onClick={HandleStartProduce}
                  disabled={!workStopState}
                >
                  {intl.formatMessage({ id: "pages.produce.autoWork" })}
                </Button>
                <Button
                  style={{ marginLeft: 10 }}
                  type="primary"
                  onClick={HandleStopProduce}
                  disabled={workStopState}
                >
                  {intl.formatMessage({ id: "pages.produce.stop" })}
                </Button>
                <Button
                  type="primary"
                  onClick={reDoFirstBoard}
                  style={{ marginLeft: 10 }}
                >
                  {intl.formatMessage({ id: "pages.produce.redoFirstBoard" })}
                </Button>
              </div>
            }
          >
            <Card.Grid
              style={{
                width: "38%",
                display: "flex",
                flexDirection: "column"
              }}
            >
              <Row style={{ display: "flex", alignItems: "center", fontSize: 16 }}>
                <span style={{ marginRight: 10, width: 50 }}>
                  {intl.formatMessage({ id: "pages.produce.connect" })}
                </span>
                {cutPlcState.isOnline ? (
                  <CircleState color="green" size={18} />
                ) : (
                  <CircleState color="red" size={18} />
                )}
              </Row>

              <Row style={{ display: "flex", alignItems: "center", fontSize: 16 }}>
                <span style={{ marginRight: 10, width: 50, marginTop: 10 }}>
                  {intl.formatMessage({ id: "pages.produce.leftCamera" })}
                </span>
                {cameraGroupState[0] ? (
                  <CircleState color="green" size={18} />
                ) : (
                  <CircleState color="red" size={18} />
                )}
              </Row>
              <Row
                style={{
                  display: "flex",
                  marginTop: 10,
                  alignItems: "center",
                  fontSize: 16
                }}
              >
                <span style={{ marginRight: 10, width: 50 }}>
                  {intl.formatMessage({ id: "pages.produce.rightCamera" })}
                </span>
                {cameraGroupState[1] ? (
                  <CircleState color="green" size={18} />
                ) : (
                  <CircleState color="red" size={18} />
                )}
              </Row>
              <Row style={{ display: "flex", fontSize: 16, marginTop: 10 }}>
                <span style={{ marginRight: 10, width: 50 }}>
                  {intl.formatMessage({ id: "pages.produce.status" })}
                </span>
                {cutPlcState.isRs ? (
                  <span style={{ color: "#FF0000" }}>
                    {intl.formatMessage({ id: "pages.produce.emergencyStop" })}
                  </span>
                ) : cutPlcState.isPause ? (
                  <span style={{ color: "#FFA500" }}>
                    {intl.formatMessage({ id: "pages.produce.pause" })}
                  </span>
                ) : cutPlcState.isRun ? (
                  <span style={{ color: "green" }}>
                    {intl.formatMessage({ id: "pages.produce.running" })}
                  </span>
                ) : (
                  <span style={{ color: "#808080" }}>
                    {intl.formatMessage({ id: "pages.produce.standby" })}
                  </span>
                )}
              </Row>
            </Card.Grid>
            <Card.Grid
              style={{
                width: "62%",
                display: "flex",
                flexDirection: "column"
              }}
            >
              <Row>
                <span style={{ color: "#595959", fontSize: 16, width: 120 }}>
                  {intl.formatMessage({ id: "pages.produce.orderNumber" })}
                </span>
                <span style={{ color: "#1890ff", fontSize: 16, marginLeft: 10 }}>
                  {workingOrder?.orderId ?? ""}
                </span>
              </Row>
              <Row style={{ marginTop: 10 }}>
                <span style={{ color: "#595959", fontSize: 16, width: 120 }}>
                  {intl.formatMessage({ id: "pages.produce.innerBoardSize" })}
                </span>
                <span style={{ color: "#1890ff", fontSize: 16, marginLeft: 10 }}>
                  {workingOrder?.width ?? ""} X {workingOrder?.height ?? ""}
                </span>
              </Row>
              <Row style={{ marginTop: 10 }}>
                <span style={{ color: "#595959", fontSize: 16, width: 120 }}>
                  {intl.formatMessage({ id: "pages.produce.taskCount" })}
                </span>
                <span
                  style={{ color: "#1890ff", fontSize: 16, marginLeft: 10, width: 80 }}
                >
                  {workingOrder?.planCount}
                </span>
              </Row>
              <Row style={{ marginTop: 10 }}>
                <span style={{ color: "#595959", fontSize: 16, width: 120 }}>
                  {intl.formatMessage({ id: "pages.produce.boardFinished" })}
                </span>
                <span style={{ color: "#1890ff", fontSize: 16, marginLeft: 10 }}>
                  {workingOrder?.finished}
                </span>
              </Row>
            </Card.Grid>
          </Card>
        </Col>
        <Col span={5} style={{ marginLeft: 10 }}>
          <Card
            style={{ height: "100%" }}
            title={
              <span style={{ color: "#595959" }}>
                {intl.formatMessage({ id: "pages.produce.orderOperation" })}
              </span>
            }
          >
            <Row>
              <span style={{ marginRight: 5, fontSize: 16 }}>
                {intl.formatMessage({ id: "pages.produce.orderNumber" })}
              </span>
              <Select
                showSearch
                style={{ width: 250 }}
                optionFilterProp="label"
                onChange={onOrderSelectChange}
                filterOption={(input, option) =>
                  option?.label?.toString().toLowerCase().includes(input.toLowerCase()) ??
                  false
                }
                options={totalOrders.map((order) => ({
                  value: order.orderId,
                  label: order.orderId,
                  key: order.key
                }))}
              />
            </Row>
            <Row style={{ marginTop: 20 }}>
              <Button type="primary" onClick={clickSearch} style={{ marginLeft: 0 }}>
                {intl.formatMessage({ id: "pages.produce.search" })}
              </Button>
              <Button type="primary" onClick={scanOrderCode} style={{ marginLeft: 15 }}>
                {intl.formatMessage({ id: "pages.produce.addOrder" })}
              </Button>
            </Row>
          </Card>
        </Col>

        <Col flex="1" style={{ marginLeft: 10 }}>
          <Card
            title={
              <span style={{ color: "#595959" }}>
                {intl.formatMessage({ id: "pages.produce.alarmLog" })}
              </span>
            }
            style={{ height: "100%" }}
            bodyStyle={{ padding: "10px" }}
            extra={
              <div
                style={{
                  display: "flex",
                  alignItems: "center"
                }}
              >
                <Button
                  type="primary"
                  onClick={clickOpenCutlineDir}
                  style={{ marginRight: 15 }}
                >
                  {intl.formatMessage({ id: "pages.produce.viewCutline" })}
                </Button>
                <Button
                  type="primary"
                  style={{ marginRight: 15 }}
                  onClick={clickOpenLogDir}
                >
                  {intl.formatMessage({ id: "pages.produce.viewLogFile" })}
                </Button>
                <Button
                  type="primary"
                  onClick={clickOpenFirstBoardCutlineDir}
                  style={{ marginRight: 15 }}
                >
                  {intl.formatMessage({ id: "pages.produce.viewFirstBoardCutline" })}
                </Button>
              </div>
            }
          >
            <AlarmRecordsForm />
          </Card>
        </Col>
      </Row>
      <Row style={{ marginTop: 20, display: "flex", justifyContent: "space-between" }}>
        <Col span={12} style={{ display: "flex", flexDirection: "column" }}>
          <Card
            title={
              <span style={{ color: "#595959" }}>
                {intl.formatMessage({ id: "pages.produce.firstBoardInfo" })}
              </span>
            }
          >
            <Card.Grid style={{ width: "65%", verticalAlign: "top" }}>
              <div style={{ textAlign: "center" }}>
                <Image
                  width={firstCutLineRes ? firstCutLineSize[0] : 350}
                  height={firstCutLineRes ? firstCutLineSize[1] : 350}
                  src={
                    firstCutLineRes ? `data:image/jpeg;base64,${firstCutLineRes}` : null
                  }
                  style={{ objectFit: "contain" }}
                  preview={{
                    mask: intl.formatMessage({ id: "pages.produce.clickToViewLarge" })
                  }}
                />
              </div>
              <Row style={{ marginTop: 10 }}>
                <span style={{ color: "#595959", fontSize: 13, width: 100 }}>
                  {intl.formatMessage({ id: "pages.produce.center1" })}
                </span>
                <span style={{ color: "#1890ff", fontSize: 13, marginLeft: 5 }}>
                  {firstCutLineRes ? catchCenter01FirstCut : "(0,0,0)"}
                </span>
              </Row>
              <Row style={{ marginTop: 10 }}>
                <span style={{ color: "#595959", fontSize: 13, width: 100 }}>
                  {intl.formatMessage({ id: "pages.produce.center2" })}
                </span>
                <span style={{ color: "#1890ff", fontSize: 13, marginLeft: 5 }}>
                  {firstCutLineRes ? catchCenter02FirstCut : "(0,0,0)"}
                </span>
              </Row>
            </Card.Grid>
            <Card.Grid style={{ width: "35%", verticalAlign: "top" }}>
              <Row style={{ marginTop: 10 }}>
                <span style={{ color: "#595959", fontSize: 13, width: 100 }}>
                  {intl.formatMessage({ id: "pages.produce.orderSize" })}
                </span>
                <span style={{ color: "#1890ff", fontSize: 13, marginLeft: 5 }}>
                  {firstCutLineRes ? workingOrder?.width : ""} X{" "}
                  {firstCutLineRes ? workingOrder?.height : ""}
                </span>
              </Row>
              <Row style={{ marginTop: 10 }}>
                <span style={{ color: "#595959", fontSize: 13, width: 100 }}>
                  {intl.formatMessage({ id: "pages.produce.recognizedSize" })}
                </span>
                <span style={{ color: "#1890ff", fontSize: 13, marginLeft: 5 }}>
                  {firstCutLineRes ? workingOrder?.calcWidth : ""} X{" "}
                  {firstCutLineRes ? workingOrder?.calcHeight : ""}
                </span>
              </Row>
              <Row style={{ marginTop: 10 }}>
                <span style={{ color: "#595959", fontSize: 13, width: 100 }}>
                  {intl.formatMessage({ id: "pages.produce.recognitionError" })}
                </span>
                <span style={{ color: "#1890ff", fontSize: 13, marginLeft: 5 }}>
                  {firstCutLineRes ? firstCalError[0] : ""} X{" "}
                  {firstCutLineRes ? firstCalError[1] : ""}
                </span>
              </Row>
              <Row style={{ marginTop: 10 }}>
                <span style={{ color: "#595959", fontSize: 13, width: 100 }}>
                  {intl.formatMessage({ id: "pages.produce.edge1" })}
                </span>
                <span style={{ color: "#1890ff", fontSize: 13, marginLeft: 5 }}>
                  {workingOrder?.firstEdge ?? "0"}
                </span>
              </Row>
              <Row style={{ marginTop: 10 }}>
                <span style={{ color: "#595959", fontSize: 13, width: 100 }}>
                  {intl.formatMessage({ id: "pages.produce.edge2" })}
                </span>
                <span style={{ color: "#1890ff", fontSize: 13, marginLeft: 5 }}>
                  {workingOrder?.secondEdge ?? "0"}
                </span>
              </Row>
              <Row style={{ marginTop: 10 }}>
                <span style={{ color: "#595959", fontSize: 13, width: 100 }}>
                  {intl.formatMessage({ id: "pages.produce.edge3" })}
                </span>
                <span style={{ color: "#1890ff", fontSize: 13, marginLeft: 5 }}>
                  {workingOrder?.thirdEdge ?? "0"}
                </span>
              </Row>
              <Row style={{ marginTop: 10 }}>
                <span style={{ color: "#595959", fontSize: 13, width: 100 }}>
                  {intl.formatMessage({ id: "pages.produce.edge4" })}
                </span>
                <span style={{ color: "#1890ff", fontSize: 13, marginLeft: 5 }}>
                  {workingOrder?.fourthEdge ?? "0"}
                </span>
              </Row>
              <Row style={{ marginTop: 10 }}>
                <span style={{ color: "#595959", fontSize: 13, width: 100 }}>
                  {intl.formatMessage({ id: "pages.produce.cutLength" })}
                </span>
                <span style={{ color: "#1890ff", fontSize: 13, marginLeft: 5 }}>
                  {firstCutLineRes ? cutBoardSizeFirst[0] : "0"}
                </span>
              </Row>
              <Row style={{ marginTop: 10 }}>
                <span style={{ color: "#595959", fontSize: 13, width: 100 }}>
                  {intl.formatMessage({ id: "pages.produce.cutWidth" })}
                </span>
                <span style={{ color: "#1890ff", fontSize: 13, marginLeft: 5 }}>
                  {firstCutLineRes ? cutBoardSizeFirst[1] : "0"}
                </span>
              </Row>
            </Card.Grid>
          </Card>
        </Col>
        <Col span={12} style={{ display: "flex", flexDirection: "column" }}>
          <Card
            title={
              <span style={{ color: "#595959" }}>
                {intl.formatMessage({ id: "pages.produce.currentJobInfo" })}
              </span>
            }
          >
            <Card.Grid style={{ width: "65%", verticalAlign: "top" }}>
              <div style={{ textAlign: "center" }}>
                <Image
                  width={notFirstCutLineRes ? notFirstImageSize[0] : 350}
                  height={notFirstCutLineRes ? notFirstImageSize[1] : 350}
                  src={
                    notFirstCutLineRes
                      ? `data:image/jpeg;base64,${notFirstCutLineRes}`
                      : null
                  }
                  style={{ objectFit: "contain" }}
                  preview={{
                    mask: intl.formatMessage({ id: "pages.produce.clickToViewLarge" })
                  }}
                />
              </div>
              <Row style={{ marginTop: 10 }}>
                <span style={{ color: "#595959", fontSize: 15, width: 100 }}>
                  {intl.formatMessage({ id: "pages.produce.center1" })}
                </span>
                <span style={{ color: "#1890ff", fontSize: 15, marginLeft: 5 }}>
                  {notFirstCutLineRes ? catchCenter01 : "(0,0,0)"}
                </span>
              </Row>
              <Row style={{ marginTop: 10 }}>
                <span style={{ color: "#595959", fontSize: 15, width: 100 }}>
                  {intl.formatMessage({ id: "pages.produce.center2" })}
                </span>
                <span style={{ color: "#1890ff", fontSize: 15, marginLeft: 5 }}>
                  {notFirstCutLineRes ? catchCenter02 : "(0,0,0)"}
                </span>
              </Row>
            </Card.Grid>
            <Card.Grid style={{ width: "35%", verticalAlign: "top" }}>
              <Row style={{ marginTop: 10 }}>
                <span style={{ color: "#595959", fontSize: 13, width: 100 }}>
                  {intl.formatMessage({ id: "pages.produce.orderSize" })}
                </span>
                <span style={{ color: "#1890ff", fontSize: 13, marginLeft: 5 }}>
                  {notFirstCutLineRes ? workingOrder?.calcWidth : ""} X{" "}
                  {notFirstCutLineRes ? workingOrder?.calcHeight : ""}
                </span>
              </Row>
              <Row style={{ marginTop: 10 }}>
                <span style={{ color: "#595959", fontSize: 13, width: 100 }}>
                  {intl.formatMessage({ id: "pages.produce.recognizedSize" })}
                </span>
                <span style={{ color: "#1890ff", fontSize: 13, marginLeft: 5 }}>
                  {notFirstCutLineRes ? calcSize[0] : ""} X{" "}
                  {notFirstCutLineRes ? calcSize[1] : ""}
                </span>
              </Row>
              <Row style={{ marginTop: 10 }}>
                <span style={{ color: "#595959", fontSize: 13, width: 100 }}>
                  {intl.formatMessage({ id: "pages.produce.recognitionError" })}
                </span>
                <span style={{ color: "#1890ff", fontSize: 13, marginLeft: 5 }}>
                  {notFirstCutLineRes ? notFirstCalError[0] : ""} X{" "}
                  {notFirstCutLineRes ? notFirstCalError[1] : ""}
                </span>
              </Row>
              <Row style={{ marginTop: 10 }}>
                <span style={{ color: "#595959", fontSize: 13, width: 100 }}>
                  {intl.formatMessage({ id: "pages.produce.edge1" })}
                </span>
                <span style={{ color: "#1890ff", fontSize: 13, marginLeft: 5 }}>
                  {workingOrder?.firstEdge ?? "0"}
                </span>
              </Row>
              <Row style={{ marginTop: 10 }}>
                <span style={{ color: "#595959", fontSize: 13, width: 100 }}>
                  {intl.formatMessage({ id: "pages.produce.edge2" })}
                </span>
                <span style={{ color: "#1890ff", fontSize: 13, marginLeft: 5 }}>
                  {workingOrder?.secondEdge ?? "0"}
                </span>
              </Row>
              <Row style={{ marginTop: 10 }}>
                <span style={{ color: "#595959", fontSize: 13, width: 100 }}>
                  {intl.formatMessage({ id: "pages.produce.edge3" })}
                </span>
                <span style={{ color: "#1890ff", fontSize: 13, marginLeft: 5 }}>
                  {workingOrder?.thirdEdge ?? "0"}
                </span>
              </Row>
              <Row style={{ marginTop: 10 }}>
                <span style={{ color: "#595959", fontSize: 13, width: 100 }}>
                  {intl.formatMessage({ id: "pages.produce.edge4" })}
                </span>
                <span style={{ color: "#1890ff", fontSize: 13, marginLeft: 5 }}>
                  {workingOrder?.fourthEdge ?? "0"}
                </span>
              </Row>
              <Row style={{ marginTop: 10 }}>
                <span style={{ color: "#595959", fontSize: 13, width: 100 }}>
                  {intl.formatMessage({ id: "pages.produce.cutLength" })}
                </span>
                <span style={{ color: "#1890ff", fontSize: 13, marginLeft: 5 }}>
                  {notFirstCutLineRes ? notFirstCutLineSize[0] : "0"}
                </span>
              </Row>
              <Row style={{ marginTop: 10 }}>
                <span style={{ color: "#595959", fontSize: 13, width: 100 }}>
                  {intl.formatMessage({ id: "pages.produce.cutWidth" })}
                </span>
                <span style={{ color: "#1890ff", fontSize: 13, marginLeft: 5 }}>
                  {notFirstCutLineRes ? notFirstCutLineSize[1] : "0"}
                </span>
              </Row>
            </Card.Grid>
          </Card>
        </Col>
      </Row>
      <TotalboardErrorModal />
      <BoardSizeCheckModal />
      <BoardSizeHandLabelModal />
      <HandInnerBoard1pinModal />
      <CutLineCheckModal />
      <DeviceLockModal />
    </div>
  )
}

export default () => (
  <App>
    <ProducePage />
  </App>
)
